package jblip.gui;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.List;

import jblip.base.HttpClient;
import jblip.gui.data.DatabaseClient;
import jblip.resources.User;
import jblip.resources.UserPicture;

public class JBlipClient extends HttpClient {
  // empty avatar for database storage (equivalent of no avatar at server)
  private static final UserPicture AV_EMPTY = new UserPicture() {
    private static final long serialVersionUID = 1L;

    @Override
    public String getURL(PictureSize size) {
      return "";
    }

    @Override
    public String getURL() {
      return "";
    }

    @Override
    public Integer getID() {
      return -1;
    }
  };

  private DatabaseClient cache;

  public JBlipClient(String username, String password) {
    super(username, password);
  }

  public JBlipClient(String host, String username, String password) {
    super(host, username, password);
  }

  @Override
  protected synchronized HttpURLConnection getConnection(String target,
      boolean auth) throws IOException {
    // superclass call ain't synchronized
    return super.getConnection(target, auth);
  }

  public synchronized boolean testLogin() {
    try {
      HttpURLConnection conn = getConnection("/login", true);
      conn.setRequestMethod("HEAD");
      final int resp = conn.getResponseCode();
      if (resp == 200) {
        return true;
      } else if (resp != 401) {
        System.err.println("Unexpected test login response: " + resp);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
    return false;
  }

  public synchronized List<String> getTrackedTags() {
    
     
    List<String> tags = new ArrayList<String>();
    
    return tags;

    /* boo, Blip sucks again (500 response code)
    try {
      final URL www_dashboard = new URL("http", "blip.pl", "/dashboard");
      final HttpURLConnection conn =
          (HttpURLConnection) www_dashboard.openConnection();

      byte[] credentials =
          (getLoggedUserName() + ":" + getLoggedUserPassword())
              .getBytes("UTF-8");
      conn.setRequestProperty("Authorization", "Basic "
          + Base64Encoder.encode(credentials));

      conn.setRequestProperty("Host", "blip.pl");
      conn.setConnectTimeout(15000);
      conn.setReadTimeout(15000);

      final BufferedReader input =
          new BufferedReader(new InputStreamReader(conn.getInputStream()));

      final Pattern re_start = Pattern.compile("<ul class=\"tags\">");
      final Pattern re_end = Pattern.compile("</ul>");
      final Pattern re_tag = Pattern.compile("<a href=\"/tags/(\\w+)\">");
      
      String next_line = null;
      boolean tags_block = false;
      while ((next_line = input.readLine()) != null) {
        if (!tags_block && re_start.matcher(next_line).find()) {
          tags_block = true;
        } else if (tags_block && re_end.matcher(next_line).find()) {
          break;
        } else if (tags_block) {
          final Matcher m_tag = re_tag.matcher(next_line);
          if (m_tag.find()) {
            tags.add(m_tag.group(1));
          }
        }
      }
      input.close();
    } catch (MalformedURLException mue) {
      mue.printStackTrace();
    } catch (IOException ioe) {
      ioe.printStackTrace();
    }

    return tags;
    */
  }

  @Override
  public synchronized UserPicture getAvatar(final Integer user_id) {
    User user = cache.getUser(user_id);
    if (user == null) {
      user = getUser(user_id);
    }

    return getAvatar(user.getLogin());
  }

  @Override
  public synchronized UserPicture getAvatar(final String user) {
    UserPicture pic = cache.getAvatar(user);
    if (pic == null) {
      pic = super.getAvatar(user);
      if (pic != null) {
        cache.setAvatar(user, pic);
      } else {
        cache.setAvatar(user, AV_EMPTY);
      }
    } else if (pic.getURL().equals("")) { // no avatar on server
      return null;
    }
    return pic;
  }

  public void setCache(final DatabaseClient db) {
    this.cache = db;
  }
}
